package com.szholly.pro.watergas_server.ps.schedule;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;
import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.common.util.RedisHelper;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import lrq.common.MyLog;

public class CreateMessage implements Job {
	
	static Logger log;
	
	/**
	 * 信息入库(推送信息入库接口)
	 * 张文成
	 * 2016年11月08日
	 */
	public static int CreateSendMessage(int SENDTYPE,String MESSAGERECEIVER,String MESSAGECONTEXT,String CONTACTWAY,int ISSEND,String GUID){
		String strSql = "";
		//生成微信报警的时候，需要先判断发送人员是否已添加微信企业号
		//若无微信企业号，则不添加该推送记录
	    if(SENDTYPE==2)
	    {
			strSql = "select * from safe_user t where t.s_userid = @MESSAGERECEIVER and t.wechatenter_id is not null";
			List<GlobalParameter> pc = new ArrayList<>();
			pc.add(new GlobalParameter("MESSAGERECEIVER", MESSAGERECEIVER));
			List<RowBase> rows = DataUtil.getSelectRows(strSql,pc);
			if(rows.size()<=0){
				return 0;
			}
	    }
		strSql = "insert into MESSAGESEND(GUID,SENDTYPE,MESSAGERECEIVER,MESSAGECONTEXT,CONTACTWAY,ISSEND,CREATETIME) "
				+ " VALUES(@GUID,@SENDTYPE,@MESSAGERECEIVER,@MESSAGECONTEXT,@CONTACTWAY,@ISSEND,sysdate)";
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("SENDTYPE", SENDTYPE));
		parms.add(new GlobalParameter("MESSAGERECEIVER", MESSAGERECEIVER));
		parms.add(new GlobalParameter("MESSAGECONTEXT", MESSAGECONTEXT));
		parms.add(new GlobalParameter("CONTACTWAY", CONTACTWAY));
		parms.add(new GlobalParameter("ISSEND", ISSEND));
		parms.add(new GlobalParameter("GUID", GUID));
		int count = DataUtil.ExecuteUpdateSql(strSql, parms);
		return count;
	}
	
	/**
	 * 根据报警信息表OP_ALAR_INFO，生成报警数据 （多阈值）
	 * 张文成
	 * 2017年05月05日
	 * @param guid
	 * @param startAlarmTime
	 */
	private void CreateSendMessageMulThr(){	
		//查找OP_ALAR_INFO中未生成推送信息的记录
		log.info("开始生成报警推送信息");
		String sql = "select t.station_code,t.start_time from OP_ALAR_INFO t "
				+ " where t.IS_CREATEMESSAGE = '0' and t.createtime > sysdate-1"
				+ " group by t.station_code,t.start_time";
		List<RowBase> groupRows = DataUtil.getSelectRows(sql, null);
		List<GlobalParameter> pc = new ArrayList<>();
		try{
			if(groupRows.size()>0){
				for(int i=0;i<groupRows.size();i++){
					RowBase groupRow = groupRows.get(i);
					String station_code = groupRow.getSafeString("station_code");
					Date start_time = groupRow.getDate("start_time");
					String mn = RedisHelper.getInstance().getMNByStationCode(station_code);
					String stationName = RedisHelper.getInstance().getStationNameByMN(mn);
				    //根据station_code与start_time查找与这组数据相关的用户，去重
					sql = "select distinct t1.user_id from OP_ALAR_INFO t"
							+" left join BC_POLL_ROLE t1 on t1.ALARM_THREHOLD_GUID = t.ALARM_THREHOLD_GUID"
							+" where t.station_code =@station_code and t.start_time = @start_time"
							+" and t1.user_id is not null ";
					pc.clear();
					pc.add(new GlobalParameter("station_code", station_code));
					pc.add(new GlobalParameter("start_time", start_time));
					List<RowBase> userRows = DataUtil.getSelectRows(sql,pc);
					if(userRows.size()>0){
						for(int e=0;e<userRows.size();e++){
							RowBase userRow = userRows.get(e);
							String user_id = userRow.getSafeString("user_id");
							String MESSAGECONTEXT = stationName + start_time + ",";
							String shortMessageGUID = UUID.randomUUID().toString();
							String wechatMessageGUID = UUID.randomUUID().toString();
							//逐用户生成具体的报警推送信息
							sql = "select t1.s_domaincaption,t1.s_unit,t.* from OP_ALAR_INFO t"
									+ " left join DATA_DEFULATDOMAIN t1 on  t1.s_domainname = 'MONITOR_PARAM' and t.param = t1.s_domaincode"
									+ " left join BC_POLL_ROLE t2 on t2.alarm_threhold_guid = t.ALARM_THREHOLD_GUID"
									+ " where t.station_code =@station_code and t.start_time = @start_time "
									+ " and t.is_createmessage = '0' and t2.user_id = @user_id";
							pc.clear();
							pc.add(new GlobalParameter("station_code", station_code));
							pc.add(new GlobalParameter("start_time", start_time));
							pc.add(new GlobalParameter("user_id", user_id));
							List<RowBase> messageRows = DataUtil.getSelectRows(sql, pc);
							//合并单条报警为一组报警
							for(int j=0;j<messageRows.size();j++){
								RowBase messageRow = messageRows.get(j);
								String pollName = messageRow.getSafeString("S_DOMAINCAPTION");
								String pollUnit = messageRow.getSafeString("S_UNIT");
								String alarmValue = messageRow.getSafeString("ALARM_VALUE");
								String alarmDownLimit = messageRow.getSafeString("ALARM_DOWNLIMIT");
								String alarmUpLimit = messageRow.getSafeString("ALARM_UPLIMIT");
								String alarmInfoGuid = messageRow.getSafeString("GUID");
								
								MESSAGECONTEXT += pollName + "监测值：" + alarmValue + pollUnit + "(阈值："+ alarmDownLimit+pollUnit+ 
										" ~ " + alarmUpLimit + pollUnit + " ) ;";
								//短信
								sql = "insert into MESSAGESEND_ALARMINFO(GUID,MESSAGEGUID,ALARMINFOGUID)"
										+" VALUES(sys_guid(),@MESSAGEGUID,@ALARMINFO_GUID)";
								pc.clear();
								pc.add(new GlobalParameter("MESSAGEGUID", shortMessageGUID));
								pc.add(new GlobalParameter("ALARMINFO_GUID", alarmInfoGuid));
								DataUtil.ExecuteUpdateSql(sql, pc);
								//微信
								sql = "insert into MESSAGESEND_ALARMINFO(GUID,MESSAGEGUID,ALARMINFOGUID)"
										+" VALUES(sys_guid(),@MESSAGEGUID,@ALARMINFO_GUID)";
								pc.clear();
								pc.add(new GlobalParameter("MESSAGEGUID", wechatMessageGUID));
								pc.add(new GlobalParameter("ALARMINFO_GUID", alarmInfoGuid));
								DataUtil.ExecuteUpdateSql(sql, pc);
							}
							MESSAGECONTEXT = MESSAGECONTEXT.substring(0, MESSAGECONTEXT.length()-1) + "。";
							//生成报警推送信息
							CreateSendMessage(1, user_id, MESSAGECONTEXT, "", 1,shortMessageGUID);  //生成短信报警记录
							CreateSendMessage(2, user_id, MESSAGECONTEXT, "", 1,wechatMessageGUID);  //生成微信报警记录	
						}
					}
					//更新OP_ALAR_INFO表字段IS_CREATEMESSAGE为已生成
					sql = "update OP_ALAR_INFO t set t.IS_CREATEMESSAGE = '1'"
							+ " where t.station_code =@station_code and t.start_time = @start_time";
					pc.clear();
					pc.add(new GlobalParameter("station_code", station_code));
					pc.add(new GlobalParameter("start_time", start_time));
					DataUtil.ExecuteUpdateSql(sql, pc);
				}
			}
				
		} catch (Exception e) {
			log.error("生成报警推送信息出错",e);
		}
	}
	
	
	/**
	 * 根据报警信息表OPERATION_ALARM_INFO，生成报警数据 （单阈值）
	 * 张文成
	 * 2017年06月15日
	 * @param guid
	 * @param startAlarmTime
	 */
	private void CreateSendMessageSingle(Date date,String alarmType,String alramValue){	
		//查找OPERATION_ALARM_INFO中未恢复的的报警
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
	
		//数据缺失、数据不变    频率：2小时一次 
		if("7".equals(alarmType)||"8".equals(alarmType))
		{
	        if(cal.get(Calendar.HOUR_OF_DAY)%2 !=0 || cal.get(Calendar.MINUTE) != 0) 
	        {
	        	return;
	        }
		}else{   //日累计流量超标   频率：24小时一次
	        if(cal.get(Calendar.HOUR_OF_DAY) != 2 || cal.get(Calendar.MINUTE) != 0) 
	        {
	        	return;
	        }
		}		
		
		log.info("开始生成"+alramValue+"报警推送信息");
		String sql = "select wm_concat(to_char(t.guid)) as alarmguid,"
				+ " wm_concat(to_char(t3.s_domaincaption)) as parmname,t1.name ,t.station_code,"
				+ " to_char(t.start_time-2/24,'YYYY-MM-DD HH24')||':00:00.0' as datatime from OP_ALAR_INFO t "
				+ " left join BC_SITE_INFO t1 on t1.code = t.station_code"
				+ " left join DATA_DEFULATDOMAIN t3 on  t3.s_domainname = 'MONITOR_PARAM' and t.param = t3.s_domaincode"
				+ " where t.IS_RECOVER != '1' and t.createtime > sysdate-1 and nvl(t.station_code,'0') != '0'"
				+ " and t.type = '"+alarmType+"'"
				+ " group by t1.name ,t.station_code,t.start_time";
		List<RowBase> groupRows = DataUtil.getSelectRows(sql, null);
		try{
			if(groupRows.size()>0){
				for(int i=0;i<groupRows.size();i++){
					RowBase groupRow = groupRows.get(i);
					String stationCode = groupRow.getSafeString("station_code");
					String stationName = groupRow.getSafeString("name");
					String parmname = groupRow.getSafeString("parmname").trim();
					String dataTime = groupRow.getSafeString("datatime");
					String[] arrAlarmGuid = groupRow.getSafeString("alarmguid").split(",");
					String MESSAGECONTEXT = stationName + dataTime + "," + parmname + alramValue +"。";
					//根据MN获取到对应发送人员
					sql = " select t1.user_id from BC_POLL_THRESHOLD t "
							+ " left join BC_POLL_ROLE t1 on t1.ALARM_THREHOLD_GUID = t.guid"
							+ " left join BC_SITE_POLL t2 on  t2.guid = t.SITE_POLLUTANTS_ID"
							+ " where  t2.site_id  = '"+stationCode+"' and t.alarm_thred_num = '"+alramValue+"' ";
					List<RowBase> userRows = DataUtil.getSelectRows(sql,null);
					if(userRows.size()>0){
						for(int e=0;e<userRows.size();e++){
							RowBase userRow = userRows.get(e);
							String user_id = userRow.getSafeString("user_id");
							//生成报警推送信息
							String shortMessageGUID =  UUID.randomUUID().toString();
							String wechatMessageGUID = UUID.randomUUID().toString();
							for(int j=0;j<arrAlarmGuid.length;j++)
							{
								//短信
								sql = "insert into MESSAGESEND_ALARMINFO(GUID,MESSAGEGUID,ALARMINFOGUID)"
										+" VALUES(sys_guid(),'"+shortMessageGUID+"','"+arrAlarmGuid[j]+"')";
								DataUtil.ExecuteUpdateSql(sql, null);
								//微信
								sql = "insert into MESSAGESEND_ALARMINFO(GUID,MESSAGEGUID,ALARMINFOGUID)"
										+" VALUES(sys_guid(),'"+wechatMessageGUID+"','"+arrAlarmGuid[j]+"')";
								DataUtil.ExecuteUpdateSql(sql, null);
							}

							CreateSendMessage(1, user_id, MESSAGECONTEXT, "", 1,shortMessageGUID);  //生成短信报警记录
							CreateSendMessage(2, user_id, MESSAGECONTEXT, "", 1,wechatMessageGUID);  //生成微信报警记录	
						}
					}
				}
			}
				
		} catch (Exception e) {
			log.error("生成"+ alramValue +"报警推送信息出错",e);
		}
	}
	
	
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		
		if(log == null){
			log = MyLog.getLogger("SendMessage");
		}
		 
		try {
			Date date = arg0.getFireTime();
			CreateSendMessageMulThr(); //先生成报警推送信息,多阈值报警
			CreateSendMessageSingle(date,"7","数据缺失"); //生成报警推送信息,数据不变、数据缺失、日累计流量缺失的数据的单阈值报警
			CreateSendMessageSingle(date,"8","数据不变"); 
			CreateSendMessageSingle(date,"9","日累计流量超标"); 
		} catch (Exception e) {
			log.error("发送信息出错",e);
		}
	}
	
	public void execute() throws JobExecutionException{
		execute(null);
	}
	
	
	/**
	 * MD5-32加密
	 * 张文成
	 * 2016年11月05日
	 */
	public static String Md5(String sourceStr){
	    String result = "";
	    try {
	        MessageDigest md = MessageDigest.getInstance("MD5");
	        md.update(sourceStr.getBytes());
	        byte b[] = md.digest();
	        int i;
	        StringBuffer buf = new StringBuffer("");
	        for (int offset = 0; offset < b.length; offset++) {
	            i = b[offset];
	            if (i < 0)
	                i += 256;
	            if (i < 16)
	                buf.append("0");
	            buf.append(Integer.toHexString(i));
	        }
	        result = buf.toString().toUpperCase();
	    } catch (NoSuchAlgorithmException e) {
	        System.out.println(e);
	    }
	    return result;
	}
	
	
	/**
	 * 调用中国网建的短信接口，执行短信发送
	 * 张文成
	 * 2016年11月05日
	 */
	public static String executeSMS(String telNum,String messageContext)
	{   
		String result = "";
		try{
			HttpClient client = new HttpClient();
			PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn"); 
			post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码
			String key = "80437cbebcc2184a9d26";
			key = Md5(key);
			NameValuePair[] data ={ new NameValuePair("Uid", "深圳浩瑞泰"),new NameValuePair("KeyMD5", key),new NameValuePair("smsMob",telNum),new NameValuePair("smsText",messageContext)};
			post.setRequestBody(data);
			client.executeMethod(post);
			result = new String(post.getResponseBodyAsString().getBytes("gbk")); 
			post.releaseConnection();
		}catch (Exception e) {
			log.error("调用短信发送接口出错",e);
		}
		return result;
	}
}
